package cn.doit.scala.day01.method

/**
 * @DATE 2021/12/24/15:16
 * @Author MDK
 * @Version 2021.2.2
 * */
object BinarySearch {
  def binarySearch(arr:Array[Int], elem:Int):Int={
    if(arr.length<= 0 || arr == null){
      return -1
    }
    var start = 0
    var end = arr.length - 1
    while (start<= end){
      val mid = (start + end)/2
      if(arr(mid) > elem){
        end = mid-1
      }else if(arr(mid) < elem){
        start = mid+1
      }else{
        return mid
      }
    }
    -1
  }

  def main(args: Array[String]): Unit = {
    val array: Array[Int] = Array[Int](1, 3, 5, 7, 8, 9, 12, 15, 18, 25, 37)
    val i = binarySearch(array, 112)
    println(s"查找的元素索引为:$i")
  }

}
